<template>
  <div class="upload-video" :class="{ 'upload-margin': margin }">
    <div class="upload-cont">
      <div v-if="isEmpty" class="empty-block">
        <icon-empty />
        <div class="text">暂无数据</div>
      </div>
      <a-upload
        v-else
        v-model:file-list="uploadValue"
        :action="uploadAction"
        :accept="accept.join(',')"
        :data="appendData"
        :disabled="disabled"
        :limit="limit"
        name="files"
        image-preview
        with-credentials
        @change="uploadChange"
        @before-upload="beforeUpload"
      >
        <template #upload-button>
          <div class="mr-0 upload-block upload-item" v-if="!disabled">
            <div class="plus">
              <icon-plus :size="14" />
            </div>
            <div class="text">上传视频</div>
            <div>支持上传{{ limit }}个</div>
          </div>
        </template>
        <template #upload-item="{ fileItem, index }">
          <div class="u-img-item upload-item" :key="index">
            <div v-if="fileItem.status == 'uploading'" class="flex items-center justify-center w-full h-full uploading">
              <div class="uploading-content">
                <p>上传中 <icon-loading /></p>
                <p>{{ getUploadingPercent(fileItem.percent) }}</p>
              </div>
            </div>
            <div class="w-full h-full" style="border: 1px solid #e5e6eb" v-if="fileItem.status == 'done'">
              <video class="w-full h-full" style="object-fit: contain" :src="fileItem.url"></video>
              <div class="action">
                <div class="btn" @click.stop="previewFn(fileItem.url)"><icon-eye /><span class="text">播放</span> </div>
                <div class="btn" @click.stop="delItem(index)" v-if="!disabled"><icon-delete /><span class="text">删除</span> </div>
              </div>
            </div>
          </div>
        </template>
      </a-upload>
    </div>
  </div>

  <video-player ref="videoPlayerRef" />
</template>

<script setup>
  import { computed, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import videoPlayer from '../preview/video-player.vue'

  const route = useRoute()

  const props = defineProps({
    modelValue: {
      type: [Array, String],
      default: () => [],
    },
    maxMB: {
      type: Number,
      default: 600,
    },
    limit: {
      type: Number,
      default: 1,
    },
    accept: {
      type: Array,
      default: () => ['.mp4', '.mov'],
    },
    disabled: Boolean,
  })
  const emit = defineEmits(['update:modelValue', 'change'])

  const isEmpty = computed(() => {
    const modelValue = props.modelValue || []
    if (props.disabled && modelValue.length == 0) {
      return true
    }
    return false
  })

  const uploadAction = import.meta.env.VITE_BASE_PATH + '/uploadFile/commonUpload'
  const appendData = { remark: route.path }
  const uploadValue = ref([])

  // 初始化 before
  const initValueWatch = watch(
    () => props.modelValue,
    (val) => {
      initValueFn(val)
    }
  )
  const initValueFn = (val) => {
    if (val && val.length > 0) {
      uploadValue.value = val.map((item) => {
        return {
          uid: item,
          name: 'image.png',
          status: 'done',
          url: `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item}`,
        }
      })
      // 关闭watch
      initValueWatch && initValueWatch()
    }
  }
  // 首先执行一次防止v-if
  initValueFn(props.modelValue)
  // 初始化 end

  // 上传之前 限制size
  let beforeUploadFileLength = 0
  const beforeUpload = (file) => {
    const isLtMB = file.size / 1024 / 1024 < props.maxMB
    if (!isLtMB) {
      Message.warning(`视频不能大于${props.maxMB}MB`)
    } else {
      beforeUploadFileLength++
    }
    return isLtMB
  }

  // 触发emit事件
  const emitEvent = () => {
    const ids = uploadValue.value.map((item) => item.uid)
    let res
    // 单个图模式的不穿数组
    if (props.single) {
      res = ids[0]
    } else {
      res = ids
      if (ids.length == 0) res = undefined
    }
    emit('update:modelValue', res)
    emit('change', res)
  }

  // 删除
  const delItem = (index) => {
    uploadValue.value.splice(index, 1)
    emitEvent()
  }

  // 修改
  const uploadChange = (fileList, file) => {
    uploadValue.value = fileList.map((item) => {
      if (item.response) {
        item.uid = item.response.result[0].fileIdStr
        item.url = `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item.uid}`
      }
      return item
    })
    if (file.status == 'done') {
      beforeUploadFileLength--
      if (beforeUploadFileLength === 0) {
        emitEvent()
      }
    }
  }

  // 上传进度
  const getUploadingPercent = (percent) => {
    // 优化进度显示
    if (percent == 1) {
      percent = 0.99
    }
    return Math.round(percent * 1000) / 10 + '%'
  }

  // 预览
  const videoPlayerRef = ref()
  const previewFn = (url) => {
    videoPlayerRef.value.open(url)
  }
</script>

<style lang="less" scoped>
  .upload-video {
    display: inline-block;
    background: #ffffff;

    .empty-block {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 103px;
      height: 77px;
      background: #f2f3f5;
      border-radius: 2px;
      border: 1px solid #e5e6eb;
      text-align: center;
      color: #b6b6b6;
      font-size: 32px;
      .text {
        font-size: 12px;
        font-weight: 400;
        color: #d8d8d8;
        line-height: 20px;
      }
    }
  }
  :deep(.arco-upload-list.arco-upload-list-type-picture-card) {
    flex-wrap: warp;
  }

  .upload-item {
    margin: 0 4px 4px 0 !important;
    width: 103px;
    height: 77px;
    .uploading {
      background: rgba(0, 0, 0, 0.5);
      color: #ffffff;
      text-align: center;
    }
  }

  .u-img-item {
    position: relative;
    font-size: 12px;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;
    &:hover {
      .action {
        display: flex;
      }
    }
    .action {
      display: none;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
      justify-content: center;
      align-content: center;
      flex-wrap: wrap;
      border-radius: 0px 0px 2px 2px;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      :hover {
        background: rgba(0, 0, 0, 0.2);
      }
      .btn {
        width: 100%;
        height: 22px;
        text-align: center;
        .text {
          margin-left: 3px;
        }
      }
    }
  }

  .upload-block {
    text-align: center;
    padding-top: 12px;
    background: #f2f3f5;
    border: 1px solid #e5e6eb;
    border-radius: 2px;
    .text {
      margin-top: 5px;
      font-size: 12px;
      font-weight: 400;
      color: #1d2129;
      line-height: 15px;
    }
    font-size: 12px;
    font-weight: 400;
    color: #86909c;
    line-height: 20px;
  }
</style>
